<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class SysBiz extends Model
{
    protected $table = 'sys_biz';
    public $timestamps = false;

    /**
     * 获取商户信息列表 + 分页搜索功能
     * 此处有一个功能，   需要查询biz_member数据表中is_staff等于0的数据   1 => 员工   0 => 不是员工
     * @return mixed
     */
    public function getBizList($biz_name)
    {
        // 商户信息表与商户用户表进行关联查询
        $list = SysBiz::where('sys_biz.name', 'like', '%'.$biz_name.'%')
            -> where(['biz_member.is_staff' => 0])
            -> rightJoin('biz_member', function ($join){
                $join -> on('sys_biz.biz_id', '=', 'biz_member.biz_id');
            })
            -> select('sys_biz.name as biz_name', 'sys_biz.*', 'biz_member.*')
            -> paginate(40);
        return $list -> toArray();
    }

    /**
     * 通过商户的主键ID获取商户的信息
     * @param int $id  商户的主键ID
     * @return mixed
     */
    public function getBizInfoById($id)
    {
        $info = SysBiz::where(['sys_biz.biz_id' => $id, 'biz_member.is_staff' => 0])
            -> leftJoin('biz_member', function ($join){
                $join -> on('sys_biz.biz_id', '=', 'biz_member.biz_id');
            })
            -> select('sys_biz.*', 'biz_member.*')
            -> first();
        if ($info){
            return $info -> toArray();
        }else{
            return false;
        }
    }

    /**
     * 通过商户的主键ID修改商户信息
     * @param $id
     * @param $setData
     * @return mixed
     */
    public function updateBizById($id, $setData)
    {
        $bol = SysBiz::where(['biz_id' => $id])
            -> update($setData);
        return $bol;
    }

    /**
     * 添加商户信息
     * @param $bizData
     * @param $memberData
     * @return bool
     */
    public function addBiz($bizData, $memberData)
    {
        DB::beginTransaction();
        try{
            $biz_id = DB::table('sys_biz') -> insertGetId($bizData);
            $memberData['biz_id'] = $biz_id;
            DB::table('biz_member') -> insertGetId($memberData);
            DB::commit();
            return true;
        }catch (\ErrorException $errorException){
            DB::rollBack();
            return false;
        }
    }

    public function updateBizId($id, $bizData, $memberData)
    {
        DB::beginTransaction();
        try {
            $bol = SysBiz::where(['biz_id' => $id]) -> update($bizData);
            DB::table("biz_member") -> where(['biz_id' => $id]) -> update($memberData);
            DB::commit();
            return true;
        }catch (\ErrorException $errorException){
            DB::rollBack();
            return false;
        }
    }
}
